
import {currentTime } from "./utils"
import EventContainer from "./event_container"
import Events from "./events"

/**
 * 触摸逻辑处理
 * 将触摸事件通过onTouchMove的方法传入之后，会回调出move事件到组件
 */
class TouchLogic {
	
	
	// 第一点触摸
	_firstPoint = {
		x: -1,
		y: -1
	};
	
	// 上一个触摸点
	_lastPoint = {
		x: -1,
		y: -1
	};
	
	// 当前关于触摸的所有数据
	_touchInfo = {
		distanceX: 0,		// 第一个点与当前的触摸点的距离
		distanceY: 0,		// 第一个点与当前的触摸点的距离
		deltaX: 0,			// 与上一个点的距离
		deltaY: 0,			// 与上一个点的距离
		speed: 0,			// 当前拖动的速度，负数表示手指向上拖动，
							// 正数表示手指向下拖动，数值为每20毫秒的位移速度
		firstPointTime: 0,	// 第一个点接触的时间
		lastPointTime: 0,	// 上一个点接触时间
	};
	
	/**
	 * 触摸开始
	 * @param {x, y} point 
	 */
	onTouchStart = (point) => {
		this._firstPoint = point;
		this._lastPoint = point;
		const time = currentTime();
		this._touchInfo.firstPointTime = time;
		this._touchInfo.lastPointTime = time;
		
		// 刹停所有速度
		this._touchInfo.speed = 0;
		this._touchInfo.distanceX = 0;
		this._touchInfo.distanceY = 0;
		this._touchInfo.deltaX = 0;
		this._touchInfo.deltaY = 0;
	};
	
	/**
	 * 触摸拖动
	 * @param {x, y} point 
	 */
	onTouchMove = (point) => {
		// 计算距离
		const deltaY = point.y - this._lastPoint.y;
		const deltaX = point.x - this._lastPoint.x;
		const now = currentTime();
		const deltaTime = now - this._touchInfo.lastPointTime;
		this._touchInfo.distanceX = point.x - this._firstPoint.x;
		this._touchInfo.distanceY = point.y - this._firstPoint.y;
		this._touchInfo.deltaX = deltaX;
		this._touchInfo.deltaY = deltaY;
		this._touchInfo.lastPointTime = now;
		this._touchInfo.speed = (parseFloat(deltaY) / parseFloat(deltaTime) * 20).toFixed(2);
		
		this._lastPoint = point;
		this._move(deltaX, deltaY, false);
	};
	
	/**
	 * 触摸结束
	 * @param {x, y} point 
	 */
	onTouchEnd = (point) => {
		// 计算距离
		const deltaY = point.y - this._lastPoint.y;
		const deltaX = point.x - this._lastPoint.x;
		const now = currentTime();
		const deltaTime = now - this._touchInfo.lastPointTime;
		this._touchInfo.distanceX = point.x - this._firstPoint.x;
		this._touchInfo.distanceY = point.y - this._firstPoint.y;
		this._touchInfo.deltaX = deltaX;
		this._touchInfo.deltaY = deltaY;
		this._touchInfo.lastPointTime = now;
		this._touchInfo.speed = (parseFloat(deltaY) / parseFloat(deltaTime) * 20).toFixed(2);
	
		
		this._lastPoint = point;
		this._move(deltaX, deltaY, true);
	};
	
	/**
	 * 私有方法，移动上层的组件
	 * @param {Object} deltaY  需要滑动的距离
	 * @param {Object} fling  移动后是否开始滑动
	 */
	_move = (deltaX, deltaY, fling) => {
		EventContainer.post(Events.MOVE, {
			deltaX,
			deltaY,
		})
		
		if(fling){
			if(this._touchInfo.speed == 0){
				return;
			}
			
			const speed = this._touchInfo.speed;
			speed = speed * 0.95	// 摩擦
			
			// TODO 惯性未完成
		}
	};
}
export default TouchLogic